<script setup lang="ts">
import useMenuBadgeStore from '@/store/modules/menuBadge'
import useSettingsStore from '@/store/modules/settings'
import dayjs from '@/utils/dayjs'
import { ElMessage } from 'element-plus'
import hotkeys from 'hotkeys-js'
import { useI18n } from 'vue-i18n'
import Provider from './ui-provider/index.vue'
import eventBus from './utils/eventBus'
import 'dayjs/locale/en'
import 'dayjs/locale/zh-cn'
import 'dayjs/locale/zh-tw'

const route = useRoute()

const settingsStore = useSettingsStore()

const menuBadgeStore = useMenuBadgeStore()

const { locale } = useI18n()
const { auth } = useAuth()
const { generateI18nTitle } = useMenu()

const isAuth = computed(() => {
  return route.matched.every((item) => {
    return auth(item.meta.auth ?? '')
  })
})

// 设置网页 title
watch([
  () => settingsStore.settings.app.enableDynamicTitle,
  () => settingsStore.title,
  () => settingsStore.customTitleList,
  () => settingsStore.lang,
], () => {
  nextTick(() => {
    if (settingsStore.settings.app.enableDynamicTitle && settingsStore.title) {
      const title = settingsStore.customTitleList.find(item => item.fullPath === route.fullPath)?.title || generateI18nTitle(settingsStore.title)
      document.title = `${title} - ${import.meta.env.VITE_APP_TITLE}`
    }
    else {
      document.title = import.meta.env.VITE_APP_TITLE
    }
  })
}, {
  immediate: true,
  deep: true,
})
let heartbeatInterval: number | null = null
let ws: WebSocket | null = null // WebSocket 实例

function startHeartbeat() {
  if (ws) {
    // 使用 window.setInterval 明确使用浏览器环境的定时器类型（返回 number）
    heartbeatInterval = window.setInterval(() => {
      if (ws?.readyState === WebSocket.OPEN) {
        ws.send(JSON.stringify({ type: 'heartbeat', message: 'ping' }))
        console.log('发送心跳消息：ping')
      }
    }, 30000) // 每 30 秒发送一次心跳消息
  }
}

function stopHeartbeat() {
  if (heartbeatInterval) {
    // 使用 window.clearInterval 清理定时器
    window.clearInterval(heartbeatInterval)
    heartbeatInterval = null
  }
}

const reconnectInterval = 5000 // 5 秒重连间隔
let reconnectTimer: number | null = null

// WebSocket 逻辑
const serverMessage = ref('') // 保存服务端消息

// 初始化 WebSocket
function setupWebSocket() {
  const username = 'sss'
  const wsUrl = `wss://www.cqwuyang.cn/ElectricManageService/webSocket/${username}`

  ws = new WebSocket(wsUrl)

  ws.onopen = () => {
    console.log('WebSocket 连接已建立')
    startHeartbeat() // 启动心跳
    if (reconnectTimer) {
      // 使用 window.clearTimeout 清理定时器
      window.clearTimeout(reconnectTimer)
      reconnectTimer = null
    }
  }

  ws.onmessage = (event) => {
    ElMessage({
      message: `有新的通知`,
      type: 'success',
    })
    console.log('服务端消息：', event.data)
    serverMessage.value = event.data
    playAudio() // 播放音频
    // window.location.reload()
  }

  ws.onclose = () => {
    stopHeartbeat() // 停止心跳
    console.log('WebSocket 连接已关闭，尝试重连...')
    // 使用 window.setTimeout 明确使用浏览器环境的定时器类型（返回 number）
    reconnectTimer = window.setTimeout(setupWebSocket, reconnectInterval) // 重新连接
  }

  ws.onerror = (error) => {
    console.error('WebSocket 错误：', error)
  }
}

// 播放音频
function playAudio() {
  const audio = new Audio('https://wuyang-1331198226.cos.ap-guangzhou.myqcloud.com/customer/69611737194387362.mp3')
  console.log('path', route.path)
  audio.play().then(() => {
    console.log('音频开始播放')
    audio.onended = () => {
      console.log('音频播放完成')
      // 判断路径是否以 "monitor_data" 结尾
      if (route.path.endsWith('warn_data') || route.path.endsWith('fault_data')) {
        console.log('路径匹配，刷新页面1')
        window.location.reload() // 仅在路径匹配时刷新页面
      }
      else {
        console.log('路径不匹配，不刷新页面1')
      }
    }
  }).catch((error) => {
    console.error('音频播放失败：', error)
    if (route.path.endsWith('warn_data') || route.path.endsWith('fault_data')) {
      console.log('路径匹配，刷新页面2')
      window.location.reload() // 仅在路径匹配时刷新页面
    }
    else {
      console.log('路径不匹配，不刷新页面2')
    }
  })
}

onMounted(async () => {
  await menuBadgeStore.fetchUnreadNumber()
  settingsStore.setMode(document.documentElement.clientWidth)
  window.addEventListener('resize', () => {
    settingsStore.setMode(document.documentElement.clientWidth)
  })
  hotkeys('alt+i', () => {
    eventBus.emit('global-system-info-toggle')
  })
  const mutedAudio = document.getElementById('muted-audio') as HTMLAudioElement
  mutedAudio.play().then(() => {
    console.log('静音音频播放成功，已获取播放权限')
  }).catch((error) => {
    console.warn('静音音频播放失败，可能无法自动播放其他音频', error)
  })

  setupWebSocket() // 初始化 WebSocket
})
// 页面卸载时关闭 WebSocket
onBeforeUnmount(() => {
  if (ws) {
    // ws.close()
  }
})

// 开启自动轮询（可选）
const stopPolling = menuBadgeStore.startAutoPolling()
// 组件卸载时停止轮询
onUnmounted(() => {
  stopPolling()
})

watch(() => settingsStore.lang, () => {
  locale.value = settingsStore.lang
})

watch(() => settingsStore.lang, () => {
  switch (settingsStore.lang) {
    case 'zh-cn':
      dayjs.locale('zh-cn')
      break
    case 'zh-tw':
      dayjs.locale('zh-tw')
      break
    case 'en':
      dayjs.locale('en')
      break
  }
}, {
  immediate: true,
})
</script>

<template>
  <Provider>
    <RouterView v-slot="{ Component }">
      <component :is="Component" v-if="isAuth" />
      <NotAllowed v-else />
    </RouterView>
    <SystemInfo />
    <!-- 隐藏的音频元素../../public/飞船报警音.mp3 -->
    <audio id="muted-audio" src="https://wuyang-1331198226.cos.ap-guangzhou.myqcloud.com/customer/69611737194387362.mp3" muted />
  </Provider>
</template>
